//
//  GDAdvertiseViewController.m
//  Gunterapple
//
//  Created by 热带雨林 on 2020/12/20.
//  Copyright © 2020 热带雨林. All rights reserved.


#import "GDAdvertiseViewController.h"
//#import <UIImageView+WebCache.h>
#import "UIImageView+WebCache.h"
#import "NSObject+BlockObserver.h"
#import "GDWebAdvertiseViewController.h"
//AV播放器倒入框架
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>
#import "UIImage+GIF.h"
#import "GDButton.h"


#define SDMainScreenBounds [UIScreen mainScreen].bounds
static NSInteger const imageViewsborderOffset = 150;

@interface GDAdvertiseViewController ()<GDWebVCDelegate,UIScrollViewDelegate>
@property (strong, nonatomic) UITabBarController *mainVC;
@property (strong, nonatomic) UINavigationController *naVC;
@property (assign, nonatomic) LaunchViewControllerType typeVC; //enum
@property (strong, nonatomic) GDButton *endButton;
@property (assign, nonatomic)BOOL adVerIsFinished; //引导页结束的标识
@property (strong, nonatomic)UIImageView *adImageView;//广告页视图
@property (nonatomic, strong) NSTimer *timer;//定时器
@property (nonatomic, strong) UILabel *timerLabel;//广告倒计时
@property (nonatomic, assign) BOOL adIsFinished;//广告已经结束了
@property (nonatomic, strong) UIView *backgroundView;
@property (nonatomic, strong) AVPlayerViewController *playerViewController;
@property (nonatomic, strong) UIImageView *keepImageView;

@end

@implementation GDAdvertiseViewController

#pragma mark - 构造方法
- (instancetype)initWithMainVC:(UITabBarController *)mainVC viewcontrollType:(LaunchViewControllerType )viewControllerType{
    if(self = [super init]){
        self.mainVC = mainVC;
        self.typeVC = viewControllerType;
        self.adVerIsFinished = NO;
        self.adTime = 5; //默认跳转时间
        self.isSkip = YES; //允许广告页跳过
        self.adIsFinished = NO;
    }
    return self;
}
#pragma mark - 全局方法 -
- (void)viewDidLoad {
    [super viewDidLoad];
    
//    @weakify(self);
    
    self.view.backgroundColor = [UIColor whiteColor];
    switch (self.typeVC) {
        case ShowLaunchAnimationViewController:{
            //动画引导页
            [self showLaunchAnimationView];
            break;
        }
        case ADLaunchViewController:{
            //广告页
            [self showAdvertiseControllView];
            //添加定时器
            self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timerSelecter) userInfo:nil repeats:YES];
            break;
        }
        case GreenhandLaunchViewController:{
            [self loadImageScrollView];
            break;
        }
        case AVLaunchViewController:{
            [self AVLaunchAnimation];
            break;
        }
        case GifBackgroundLaunchViewController:{
            [self loadGifImageView];
            break;
        }
        default:
            break;
    }
}

#pragma mark - 动画图片 -
- (void)showLaunchAnimationView{
    UIView *backgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, GDScreenW,GDScreenH)];
    [self.view addSubview:backgroundView];
    self.backgroundView = backgroundView;
    UIImage *image =  [UIImage imageNamed:@"fx_launchimage_bg"];
    UIImageView *viewImage = [[UIImageView alloc]initWithImage:image];
    viewImage.frame = CGRectMake(0, 0, GDScreenW + imageViewsborderOffset, GDScreenH);
    //autoresizingMask  contentMode
    viewImage.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    //注意 fill是充满 fit 是合适的情况
    viewImage.contentMode = UIViewContentModeScaleAspectFill;
    [backgroundView addSubview:viewImage];
    UIImage *imageIcon = [UIImage imageNamed:@"fx_launchimage_front"];
    UIImageView *imageIconView = [[UIImageView alloc]initWithImage:imageIcon];
    imageIconView.frame = CGRectMake(0, 0, GDScreenW, GDScreenH);
    [backgroundView addSubview:imageIconView];
    
    [backgroundView addSubview:self.endButton];
    //动画
    [UIView animateWithDuration:6.0f delay:0.0f options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveLinear animations:^{
        NSInteger randomTranslationValueX = imageViewsborderOffset - 100;
        NSInteger randomTranslationValueY = 0;
        CGAffineTransform translationTransform = CGAffineTransformMakeTranslation(randomTranslationValueX, randomTranslationValueY);
        CGFloat randomScaleTransformValue = 1.0f;
        CGAffineTransform scaleTransform = CGAffineTransformMakeScale(randomScaleTransformValue, randomScaleTransformValue);
        viewImage.transform = CGAffineTransformConcat(scaleTransform, translationTransform);
    } completion:^(BOOL finished) {
        //注意如果动画没有结束就进行跳转，下面的方法会跳转两次，出现问题
        if(self.adVerIsFinished == NO){
            [self navigationRootVC];
        }else{
            //动画结束了什么都不做
        }
    }];
}

#pragma mark - 广告页
- (void)showAdvertiseControllView{
    self.adImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, GDScreenW, GDScreenH)];
    GDWeakSelf
    [self.adImageView sd_setImageWithURL:[NSURL URLWithString:self.imageURL] placeholderImage:[UIImage imageNamed:@"newbackImage"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        //图片加载完毕
        weakSelf.adImageView.image = image;
//        [weakSelf.timer fire];
    }];
    [self.view addSubview:self.adImageView];
    //添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(jumpToAdvertiseView)];
    [self.adImageView addGestureRecognizer:tap];
    [self.adImageView setUserInteractionEnabled:YES];
    //添加时间提示
    [self.adImageView addSubview:self.timerLabel];
    
}
#pragma mark - 广告页图片加载
- (void)setImageURL:(NSString *)imageURL{
    _imageURL = imageURL;
}

#pragma mark - 跳转到网页广告
- (void)jumpToAdvertiseView{
    //跳转时 时间没结束 需要timer 与mode 解除持有关系 解除关系之后定时器会停掉
    [self.timer invalidate];
    self.timer = nil;
    //已经进入到动画页没有返回
    self.adIsFinished = YES;
    /**
     1.代理方式实现广告页返回
     */
    GDWebAdvertiseViewController *webVC = [[GDWebAdvertiseViewController alloc]init];
    //弹出谁，设置谁的样式,弹出的是webVC，就需要修改webVC的弹出样式
//    webVC.modalPresentationStyle = 0;
//    webVC.delegate = self;
    /**
     2.使用通知实现从广告页的返回 失败
     */
   //    [[NSNotificationCenter defaultCenter] postNotificationName:@"pushtoad" object:nil];
//    [self navigationRootVC];
    /**
     3.通过属性进行赋值,  能够实现直接返回根控制器的效果
     */
//    指定根控制器
//    self.naVC = [[UINavigationController alloc]initWithRootViewController:self.mainVC];
    //根控制器赋值
    webVC.mainNaVC = self.naVC;
    webVC.urlStr = self.URLStr;
    [self presentViewController:webVC animated:nil completion:nil];
    
}
/**
广告页中通过代理来实现回到根控制器
 */
- (void)bakcNa{
    [self navigationRootVC];
}
#pragma mark - 新手引导页
- (void)loadImageScrollView{
    //添加scrollView
    UIScrollView *imageScrollView = [[UIScrollView alloc]initWithFrame:GDScreenBounds];
    //指定代理
    imageScrollView.delegate = self;
    //图片数组并且没有网络图片数组
    if(self.imageArray.count != 0 && self.imageURLArray.count == 0){
        //设置scrollView的内容尺寸
        imageScrollView.contentSize = CGSizeMake(GDScreenW * self.imageArray.count, GDScreenH);
        //设置分页,滑动时会自动滚动到下一页
        imageScrollView.pagingEnabled = YES;
        //取消进度条
        imageScrollView.showsVerticalScrollIndicator = NO;
        imageScrollView.showsHorizontalScrollIndicator = NO;
        //取消弹性
        imageScrollView.bounces = NO;
        for(int i = 0;i<self.imageArray.count; i++){
            //图片布局 需要根据自己的位置进行布局
            UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(GDScreenW * i, 0, GDScreenW, GDScreenH)];
            imageView.image = [UIImage imageNamed:self.imageArray[i]];
            [imageScrollView addSubview:imageView];
            //最后一张图片需要添加进入按钮
            if(i == self.imageArray.count - 1){
                [imageView addSubview:self.endButton];
                //允许交互
                imageView.userInteractionEnabled = YES;
            }
        }
    }
    //加载网络图片
    if(self.imageURLArray.count != 0){
        imageScrollView.contentSize = CGSizeMake(GDScreenW *self.imageURLArray.count, GDScreenH);
        imageScrollView.showsVerticalScrollIndicator = NO;
        imageScrollView.showsHorizontalScrollIndicator = NO;
        imageScrollView.pagingEnabled = YES;
        imageScrollView.bounces = NO;
        for(int i=0;i<self.imageURLArray.count;i++){
            UIImageView *imageScrView = [[UIImageView alloc]initWithFrame:CGRectMake(GDScreenW * i, 0, GDScreenW, GDScreenH)];
            [imageScrView sd_setImageWithURL:[NSURL URLWithString:self.imageURLArray[i]]];
            [imageScrollView addSubview:imageScrView];
            if(i == self.imageURLArray.count - 1){
                [imageScrollView addSubview:self.endButton];
            }
        }
    }
    //
    [self.view addSubview:imageScrollView];
    [self.view addSubview:self.pageControl];
    self.pageControl.numberOfPages = self.imageArray.count;
}
#pragma mark - scrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    //将偏移量转成页数
    NSInteger pageNum = scrollView.contentOffset.x / GDScreenW;
    self.pageControl.currentPage = pageNum;
}
#pragma mark - 开机动画
- (void)AVLaunchAnimation{
    //mp4URL
//    NSURL *mp4Url =  [[NSURL alloc]initFileURLWithPath:self.mp4URLStr];
//    [self.view addSubview:self.playerViewController.view];
//    self.mp4URLStr = [self.mp4URLStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"#%^{}\"[]|\\<> "].invertedSet];
    /**
     //获取本地视频路径
     NSString* localFilePath=[[NSBundle mainBundle]pathForResource:@"keep" ofType:@"mp4"];
     NSURL *mp4Url = [NSURL fileURLWithPath:localFilePath];
     
     //网络视频路径
     NSString *webVideoPath = @"http://api.junqingguanchashi.net/yunpan/bd/c.php?vid=/junqing/1129.mp4";
     NSURL *webVideoUrl = [NSURL URLWithString:webVideoPath];
     */
    NSURL *mp4Url = [NSURL fileURLWithPath:self.mp4URLStr];
    //获取本地视频方法错误
//    NSURL *mp4Url = [NSURL URLWithString:self.mp4URLStr];
    self.playerViewController = [[AVPlayerViewController alloc]init];
    AVPlayer *player = [AVPlayer playerWithURL:mp4Url];
    self.playerViewController.view.frame = GDScreenBounds;
    //视频播放器进度条显示
    self.playerViewController.showsPlaybackControls = NO;
    //视频播放器画面全屏
    self.playerViewController.videoGravity = AVLayerVideoGravityResizeAspectFill;
    ///开启这个播放的时候支持（全屏）横竖屏哦
//    self.playerViewController.entersFullScreenWhenPlaybackBegins = YES;
    //开启这个所有 item 播放完毕可以退出全屏
//    self.playerViewController.exitsFullScreenWhenPlaybackEnds = YES;
    [self.view addSubview:self.playerViewController.view];
    self.playerViewController.player = player;
    
    //是否加载好，播放
//    if(self.playerViewController.readyForDisplay)
    [self.playerViewController.player play];
    
    //在视图上添加其他功能按钮
    [self.view addSubview:self.keepImageView];
    [self.view addSubview:self.endButton];
    //通过分类监听视频播放完毕，添加进入应用按钮
     [self HF_addNotificationForName:AVPlayerItemDidPlayToEndTimeNotification
                               block:^(NSNotification *notification) {
//         [self.view addSubview:self.endButton];
     }];
    
    //观察status属性，可以在加载成功之后获得视频长度
    [self.playerViewController.player.currentItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:NULL];
    
    //观察loadedTimeRanges属性，可以获得缓存进度，获得缓冲进度条
    [self.playerViewController.player.currentItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:NULL];
    
}
#pragma mark - gif动图
- (void)loadGifImageView{
//    self.view.backgroundColor = [UIColor colorWithRed:29 green:32 blue:33 alpha:0];
    UIImageView *backImageView = [[UIImageView alloc]initWithFrame:GDScreenBounds];
    [self.view addSubview:backImageView];
    backImageView.image = [UIImage imageNamed:@"gifBack"];
    [backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
    }];
    
    UIImageView *gifImageView = [[UIImageView alloc]init];
    if(self.gifImageStr != nil && self.gifImageUrlStr == nil){
        gifImageView.image = [UIImage sd_animatedGIFNamed:self.gifImageStr];
    }else{
        [gifImageView sd_setImageWithURL:[NSURL URLWithString:self.gifImageUrlStr]];
    }
    [self.view addSubview:gifImageView];
    [self.view addSubview:self.endButton];
    
    [gifImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
        make.width.mas_equalTo(GDScreenW);
        make.height.mas_equalTo(GDScreenW - 70);
    }];
}

#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    //获得AVPlayerItem
    AVPlayerItem *playerItem = (AVPlayerItem *)object;
    if([keyPath isEqualToString:@"status"]){
        //获取playerItem的status属性最新的状态
        AVPlayerStatus status = [[change valueForKey:@""] index];
        switch (status) {
            case AVPlayerStatusReadyToPlay:{
//                //获取视频长度
//                CMTime duration = playerItem.duration;
//                //更新显示:视频总时长(自定义方法显示时间的格式)
//                self.totalNeedPlayTimeLabel.text = [self formatTimeWithTimeInterVal:CMTimeGetSeconds(duration)];
//                //开启滑块的滑动功能
//                self.sliderView.enabled = YES;
//                //关闭加载Loading提示
//                [self showaAtivityInDicatorView:NO];
//                //开始播放视频
//                [self.player play];
                 break;
            }
               
            case AVPlayerStatusFailed:{
//                [self showaAtivityInDicatorView:NO];//关闭Loading视图
//                self.playerInfoButton.hidden = NO; //显示错误提示按钮，点击后重新加载视频
//                [self.playerInfoButton setTitle:@"资源加载失败，点击继续尝试加载" forState: UIControlStateNormal];
                 break;
            }
               
            case AVPlayerStatusUnknown:{
                NSLog(@"加载遇到未知问题:AVPlayerStatusUnknown");
                break;
            }
                
            default:
                break;
        }
    }else if([keyPath isEqualToString:@"loadedTimeRanges"]){
//        //获取视频缓冲进度数组，这些缓冲的数组可能不是连续的
//        NSArray *loadedTimeRanges = playerItem.loadedTimeRanges;
//        //获取最新的缓冲区间
//        CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];
//        //缓冲区间的开始的时间
//        NSTimeInterval loadStartSeconds = CMTimeGetSeconds(timeRange.start);
//        //缓冲区间的时长
//        NSTimeInterval loadDurationSeconds = CMTimeGetSeconds(timeRange.duration);
//        //当前视频缓冲时间总长度
//        NSTimeInterval currentLoadTotalTime = loadStartSeconds + loadDurationSeconds;
//        //NSLog(@"开始缓冲:%f,缓冲时长:%f,总时间:%f", loadStartSeconds, loadDurationSeconds, currentLoadTotalTime);
//        //更新显示：当前缓冲总时长
//        _currentLoadTimeLabel.text = [self formatTimeWithTimeInterVal:currentLoadTotalTime];
//        //更新显示：视频的总时长
//        _totalNeedLoadTimeLabel.text = [self formatTimeWithTimeInterVal:CMTimeGetSeconds(self.player.currentItem.duration)];
//        //更新显示：缓冲进度条的值
//        _progressView.progress = currentLoadTotalTime/CMTimeGetSeconds(self.player.currentItem.duration);
    }
}
#pragma mark - 返回UINavigationController的根控制器 -
- (void)navigationRootVC{
//    [self.view.layer removeAllAnimations]; //移除动画失败
    self.adVerIsFinished = YES;
    self.adIsFinished = YES;
    self.timer = nil;
    self.playerViewController = nil;
    
    //重新指定根控制器并展示
//    self.naVC = [[UINavigationController alloc]initWithRootViewController:self.mainVC];
    
//    self.view.window.rootViewController = self.naVC;
    self.view.window.rootViewController = self.mainVC;
    
}
#pragma mark - 定时器方法
- (void)timerSelecter{
    if(self.isSkip){
        self.timerLabel.text = [NSString stringWithFormat:@"跳过广告%ld",self.adTime];
        self.adTime --;
        if(self.adTime < 0){
            [self.timer invalidate];
            if(self.adIsFinished == NO)//定时器没有结束就跳转到主页，就不需要再指定根控制器
                [self navigationRootVC];
        }
    }else{
        //不允许跳过广告
        self.timerLabel.text = [NSString stringWithFormat:@"广告剩余%ld",self.adTime];
        self.adTime --;
        if(self.adTime < 0){
            [self.timer invalidate];
            if(self.adIsFinished == NO) //同上
                [self navigationRootVC];
        }
    }
}
#pragma mark -转换时间格式的方法
- (NSString *)formatTimeWithTimeInterVal:(NSTimeInterval)timeInterVal{
    int minute = 0, hour = 0, secend = timeInterVal;
    minute = (secend % 3600)/60;
    hour = secend / 3600;
    secend = secend % 60;
    return [NSString stringWithFormat:@"%02d:%02d:%02d", hour, minute, secend];
}
#pragma mark - 跳转按钮 lazy
- (UIButton *)endButton{
    if(!_endButton){
        _endButton = [[GDButton alloc]initWithFrame:CGRectZero];
        _endButton.frame = CGRectMake(GDScreenW / 2 -60, GDScreenH - 120, 120, 40);
        [_endButton setTitle:@"enter" forState:UIControlStateNormal];
        [_endButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _endButton.titleLabel.font = [UIFont systemFontOfSize:30];
        [_endButton setImage:[UIImage imageNamed:@"APC_timeLineIcon"] forState:UIControlStateNormal];
        _endButton.layer.cornerRadius = 10.0;
        _endButton.layer.masksToBounds = YES;
        _endButton.layer.borderWidth = 1.0f;
        _endButton.layer.borderColor = [UIColor whiteColor].CGColor;
        _endButton.titleRect = CGRectMake(10.0, 3.0, 100, 30);
        _endButton.imageRect = CGRectMake(100, 5.0, 30, 30);
        [_endButton layoutIfNeeded];
        [_endButton addTarget:self action:@selector(navigationRootVC) forControlEvents:UIControlEventTouchUpInside];
    }
    return _endButton;
}
- (UIPageControl *)pageControl{
    if(!_pageControl){
        _pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(0, GDScreenH -  40, GDScreenW, 40)];
        _pageControl.currentPage = 0;
        _pageControl.currentPageIndicatorTintColor = [UIColor blueColor];
        _pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
    }
    return _pageControl;
}
- (UILabel *)timerLabel{
    if (!_timerLabel) {
        _timerLabel = [[UILabel alloc]initWithFrame:CGRectMake(GDScreenW - 120, 40, 100, 40)];
        _timerLabel.backgroundColor = [UIColor colorWithRed:125/256.0 green:125/256.0  blue:125/256.0  alpha:0.5];
        _timerLabel.textColor = [UIColor whiteColor];
        _timerLabel.textAlignment = NSTextAlignmentCenter;
        _timerLabel.layer.masksToBounds = YES;
        _timerLabel.layer.cornerRadius = 5.0f;
        [_timerLabel setUserInteractionEnabled:YES];
        //添加手势
        UITapGestureRecognizer *timerLabelTap =  [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(navigationRootVC)];
        [_timerLabel addGestureRecognizer:timerLabelTap];
    }
    return _timerLabel;
}
//- (AVPlayerViewController *)playerViewController{
//    if(!_playerViewController){
//        _playerViewController = [[AVPlayerViewController alloc]init];
//        //视图的填充模式
//        _playerViewController.videoGravity = AVLayerVideoGravityResizeAspectFill;
//        //是否显示播放器控制条
//        _playerViewController.showsPlaybackControls = NO;
//        //显示的尺寸
//        _playerViewController.view.frame = GDScreenBounds;
//
//    }
//    return _playerViewController;
//}
- (UIImageView *)keepImageView{
    if(!_keepImageView){
        UIImage *image = [UIImage imageNamed:@"keep"];
        _keepImageView = [[UIImageView alloc]initWithImage:image];
        _keepImageView.frame = CGRectMake((GDScreenW - image.size.width) * 0.5, GDScreenH * 0.25, image.size.width, image.size.height);
    }
    return _keepImageView;
}
#pragma mark - dealloc
- (void)dealloc{
    //释放资源
    self.playerViewController = nil;
    if(self.timer != nil){
        [self.timer invalidate];
        self.timer = nil;
    }else{
        
    }
}



@end
